package com.kanshu.ksgb.fastread.doudou.common.hotfix;

import android.text.TextUtils;
import android.util.Log;

import com.kanshu.ksgb.fastread.doudou.app.Xutils;
import com.kanshu.ksgb.fastread.doudou.common.hotfix.tinker.TinkerHelper;
import com.kanshu.ksgb.fastread.doudou.common.net.ResponseData;
import com.kanshu.ksgb.fastread.doudou.common.net.SuperCallBack;
import com.kanshu.ksgb.fastread.doudou.common.net.retrofit.RetrofitHelper;
import com.kanshu.ksgb.fastread.doudou.common.util.FileUtils;
import com.kanshu.ksgb.fastread.doudou.common.util.ThreadPoolUtil;
import com.kanshu.ksgb.fastread.doudou.common.util.Utils;
import com.kanshu.ksgb.fastread.doudou.common.business.manager.MMKVDefaultManager;

import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

import retrofit2.Call;

public class PatchUtils {

    public static void checkPatch() {
        TinkerRequestParams params = new TinkerRequestParams();
        RetrofitHelper.getInstance().createService(PatchService.class).checkPatchVersion(params).enqueue(new SuperCallBack<PatchInfo>() {
            @Override
            public void onSuccess(Call<ResponseData<PatchInfo>> call, PatchInfo serverData) {
                int appPatchVersion = MMKVDefaultManager.getInstance().getPatchVersion();
                int serverPatchVersion = serverData == null ? 0 : Integer.parseInt(serverData.getVersion_code());
                Log.i("Tinker patch","Server patch version: " + (serverData == null ? "none" : serverData.getPatch_version()) + "   App patch version:" + appPatchVersion);
                if (serverData != null && Utils.getVersionCode(Xutils.sContext) == Integer.parseInt(serverData.getVersion_code()) ) {
                    if(appPatchVersion == serverPatchVersion && "2".equals(serverData.using_state)){
                        //停用状态，卸载补丁
                        Log.i("Tinker patch","patch disabled, uninstall patch");
                        TinkerHelper.removePatch();
                        MMKVDefaultManager.getInstance().setPatchVersion(0);
                        return;
                    }

                    if(appPatchVersion < serverPatchVersion && !"2".equals(serverData.using_state)){
                            //Let's download patch and install
                            if (!TextUtils.isEmpty(serverData.getUpgrade_download_url())) {
                                Log.i("Tinker patch","downloading patch...");
                                downLoadPatch(serverData);
                            }
                    }
                }
            }

            @Override
            public void onFailure(Call<ResponseData<PatchInfo>> call, Throwable t) {
                super.onFailure(call, t);
                Log.i("Tinker patch","get patch failed from server");
            }
        });
    }


    /**
     * 从服务器下载文件
     */
    public static void downLoadPatch(final PatchInfo info) {
        ThreadPoolUtil.getInstance().addTask(() -> {
            String path = info.getUpgrade_download_url();
            try {
                URL url = new URL(path);
                HttpURLConnection con = (HttpURLConnection) url.openConnection();
                con.setReadTimeout(5000);
                con.setConnectTimeout(5000);
                con.setRequestProperty("Charset", "UTF-8");
                con.setRequestMethod("GET");
                if (con.getResponseCode() == 200) {
                    InputStream is = con.getInputStream();//获取输入流
                    FileOutputStream fileOutputStream = null;//文件输出流
                    if (is != null) {
                        fileOutputStream = new FileOutputStream(FileUtils.getPatchFile());//指定文件保存路径，代码看下一步
                        byte[] buf = new byte[1024];
                        int ch;
                        while ((ch = is.read(buf)) != -1) {
                            fileOutputStream.write(buf, 0, ch);//将获取到的流写入文件中
                        }
                    }
                    if (fileOutputStream != null) {
                        fileOutputStream.flush();
                        fileOutputStream.close();
                        is.close();
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
                Log.i("Tinker patch","download patch failed: " + e.getMessage());
                return;
            }
            MMKVDefaultManager.getInstance().setPatchVersion(Integer.parseInt(info.getPatch_version()));
            TinkerHelper.loadPatch();
        });
    }

}
